<?php

require_once(WSB_XTENSION_PATH . 'filelinks/models/DbTable/Table.php');

class Filelinks_IndexController extends WSB_Xtension_Content
{

	public function indexAction()
	{
		$table = $this->getTable();
		$where = $table->getAdapter()->quoteInto('id=?', $this->_container->item_id);
		$row = $table->fetchRow($where);
		if($row instanceof WSB_Db_Row) {
			$links = WSB_Div::csvToArray($row->links, ',');
			$labels = WSB_Div::csvToArray($row->labels, "\n");
			$descriptions = WSB_Div::csvToArray($row->descriptions, "\n");
			$i = 0;
			$filelinks = array();
			foreach($links AS $link) {
				if(is_file(WSB_PATH . $link)) {

					$label = empty($labels[$i]) ? basename($link) : trim($labels[$i]);
					$description = empty($descriptions[$i]) ? '' : trim($descriptions[$i]);
					$filesize = $this->_getFilesize($link);
					$filesizeHuman = $this->_getHumanReadableFilesize($filesize);
					$extension = $this->_getExtension($link);
					$preview = ($row->layout == 2) ? $this->_getPreview($link, $extension) : '';

					// "Sicheren" Dateilink erzeugen
					$isSecure = $this->_isSecure($link);
					if($isSecure) {
						$url = WSB_Xtension_Url::getInstance();
						$link = $url->getHrefToThisPage(array('filelinks' => array('action' => 'download', 'id' => $this->_container->item_id, 'index' => $i)));
					}

					$filelinks[] = array(
						'label' => $label,
						'href' => $link,
						'description' => $description,
						'extension' => $extension,
						'icon' => strtolower($extension),
						'preview' => $preview,
						'filesize' => $filesize,
						'filesize_human' => $filesizeHuman,
						'fileinfo' => $row->show_fileinfo ? $this->_renderFileinfo($filesizeHuman, $extension) : ''
					);

				}
				$i++;
			}

			$this->_view->layout = $row->layout;
			$this->_view->filelinks = $filelinks;

			$viewscript = sprintf('index-layout-%d.phtml', intval($row->layout));
			$this->addContent($this->_view->render($viewscript));

		}

	}

	public function downloadAction()
	{
		$id = intval($this->getParam('id'));
		$index = intval($this->getParam('index'));
		if(intval($this->_container->item_id) === $id) {
			$table = $this->getTable();
			$where = $table->getAdapter()->quoteInto('id=?', $id);
			$row = $table->fetchRow($where);
			if($row instanceof WSB_Db_Row) {
				$links = WSB_Div::csvToArray($row->links, ',');
				if(array_key_exists($index, $links)) {
					$filepath = $links[$index];
					if(is_file($filepath)) {

						// FileInfo Objekt erzeugen
						$fileinfo = new WSB_Fileinfo($filepath);

						// Open the file in a binary mode
						$fp = fopen($fileinfo->getPathname(), 'rb');

						// Send the right headers
						header(sprintf('Content-disposition: inline; filename="%s"', $fileinfo->getFilename()));
						header(sprintf('Content-type: %s; name="%s', $fileinfo->getMimeType(), $fileinfo->getFilename()));
						header("Content-Length: " . $fileinfo->getSize());
						header("Pragma: no-cache");
						header("Expires: 0");

						// Send the file and stop the script
						fpassthru($fp);

						fclose($fp);
						exit;
					}
				}
			}
		}
	}

	private function _getPreview($link, $extension)
	{
		if(in_array($extension, array('GIF', 'JPG', 'JPEG', 'PNG'))) {
			$image = new WSB_Image($link);
			$scaled = $image->getScaledImage(100, 0);
			return $scaled->getRelativePath();
		}
		return '';
	}

	private function _getExtension($link)
	{
		return strtoupper(WSB_Div::getFileExtension(WSB_PATH . $link));
	}

	private function _getFilesize($link)
	{
		return filesize(WSB_PATH . $link);
	}

	private function _getHumanReadableFileSize($filesize)
	{
		return WSB_Div::getHumanReadableFileSize($filesize);
	}

	/**
	 * Fileinfos erstellen (XHTML)
	 *
	 * @param int $size
	 * @param string $extension
	 * @return string
	 */
	private function _renderFileinfo($size, $extension)
	{
		return sprintf('<span class="fileinfo"> (<span class="extension">%s, </span><span class="size">%s</span>)</span>', $extension, $size);
	}

	private function _renderFilesize($link)
	{
		$extension = $this->_getExtension($link);
		$filesize = $this->_getFilesize($link);
		return sprintf('<span class="fileinfo"> (<span class="extension">%s, </span><span class="size">%s</span>)</span>', $extension, $filesize);
	}

	public function getTable()
	{
		return new Filelinks_Model_DbTable_Table();
	}

	private function _getSecurePaths()
	{
		$config = $this->getConfiguration();
		$securePathsCsv = isset($config->securePaths) ? $config->securePaths : '';
		return WSB_Div::explode(',', $securePathsCsv);
	}

	private function _isSecure($file)
	{
		foreach($this->_getSecurePaths() AS $path) {
			$pos = strpos($file, $path);
			if($pos === 0) {
				return true;
			}
		}
		return false;
	}

}
